package com.xjrsoft.module.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageInput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.system.dto.AddDeveloperDto;
import com.xjrsoft.module.system.dto.DeveloperAuthDto;
import com.xjrsoft.module.system.dto.UpdateDeveloperDto;
import com.xjrsoft.module.system.entity.Developer;
import com.xjrsoft.module.system.entity.DeveloperAuth;
import com.xjrsoft.module.system.service.IDeveloperAuthService;
import com.xjrsoft.module.system.service.IDeveloperService;
import com.xjrsoft.module.system.vo.DeveloperListVo;
import com.xjrsoft.module.system.vo.DeveloperVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 开发者表 前端控制器
 * </p>
 *
 * @author zlf
 * @since 2024-03-15
 */
@RestController
@RequestMapping(GlobalConstant.SYSTEM_MODULE_PREFIX + "/developer")
@Api(value = GlobalConstant.SYSTEM_MODULE_PREFIX + "/developer", tags = "开发者管理")
@AllArgsConstructor
public class DeveloperController {
    
    private final IDeveloperService developerService;

    private final IDeveloperAuthService developerAuthService;

    @GetMapping("/page")
    @ApiOperation("查询开发者列表数据(分页)")
    public R page(@Valid PageInput dto) {
        IPage<DeveloperListVo> page = developerService.selectJoinListPage(ConventPage.getPage(dto), DeveloperListVo.class,
                MPJWrappers.<Developer>lambdaJoin()
                        .disableSubLogicDel()
                        .select(Developer::getId)
                        .select(Developer.class, x -> VoToColumnUtil.fieldsToColumns(DeveloperListVo.class).contains(x.getProperty()))
                        .leftJoin(User.class, User::getId, Developer::getCreateUserId, ext -> ext.selectAs(User::getName, DeveloperListVo::getCreateUserName))
                        .and(StrUtil.isNotEmpty(dto.getKeyword()),
                                wrapper -> wrapper.like(Developer::getName, dto.getKeyword()).or().like(Developer::getCode, dto.getKeyword()))
                        .orderByDesc(Developer::getCreateDate));
        return R.ok(ConventPage.getPageOutput(page));
    }

    @GetMapping("/info")
    @ApiOperation("查询开发者详情数据")
    public R info(@RequestParam Long id) {
        Developer developer = developerService.getById(id);
        return R.ok(BeanUtil.toBean(developer, DeveloperVo.class));
    }


    @PostMapping
    @ApiOperation(value = "新增开发者")
    public R add(@Valid @RequestBody AddDeveloperDto dto) {
        Developer developer = BeanUtil.toBean(dto, Developer.class);
        return R.ok(developerService.save(developer));
    }

    @PutMapping
    @ApiOperation(value = "更新开发者")
    public R update(@Valid @RequestBody UpdateDeveloperDto dto){
        Developer developer = BeanUtil.toBean(dto, Developer.class);
        return R.ok(developerService.updateById(developer));
    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    public R delete(@RequestBody List<Long> ids) {
        if (ids.contains(1L)) {
            return R.error("不能删除主系统！");
        }
        return R.ok(developerService.removeBatchByIds(ids));
    }

    @PostMapping("/auth")
    @ApiOperation(value = "开发者授权")
    public R setAuth(@RequestBody DeveloperAuthDto dto) {
        Long id = dto.getId();
        List<DeveloperAuth> authList = new ArrayList<>();
        for (String interfaceId : dto.getInterfaceIds()) {
            DeveloperAuth developerAuth = new DeveloperAuth();
            developerAuth.setDevId(id);
            developerAuth.setInterfaceId(interfaceId);
            authList.add(developerAuth);
        }
        // 先清除权限
        developerAuthService.remove(Wrappers.lambdaQuery(DeveloperAuth.class).eq(DeveloperAuth::getDevId, id));
        if (CollectionUtils.isNotEmpty(authList)) {
            developerAuthService.saveBatch(authList);
        }
        return R.ok();
    }

    @GetMapping("/auth")
    @ApiOperation(value = "获取开发者授权的接口id")
    public R setAuth(@RequestParam Long id) {
        List<DeveloperAuth> developerAuthList = developerAuthService.list(
                Wrappers.lambdaQuery(DeveloperAuth.class).eq(DeveloperAuth::getDevId, id));
        List<String> resultList = new ArrayList<>();
        for (DeveloperAuth auth : developerAuthList) {
            resultList.add(auth.getInterfaceId());
        }
        return R.ok(resultList);
    }
}
